import React, {Component} from 'react';
import {View,Text,ActivityIndicator,Image,FlatList,TouchableHighlight} from 'react-native'
import {Actions} from 'react-native-router-flux'

class MovieList extends Component {
  constructor(props){
    super(props)
    this.state = {
      movie: [],
      nowPage: 1,
      pageSize: 15,
      totalPage: 0,
      isLoading: true
    }
  }
  UNSAFE_componentWillMount(){
    this.getMoviesByPage()
  }
  
  render() {
    return <View>
      {this.renderList()}
    </View>
  }
  
  // 获取电影列表数据
  getMoviesByPage = () => {
    const start = this.state.pageSize*(this.state.nowPage - 1)
    const url = `http://api.douban.com/v2/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a&start=${start}&count=${this.state.pageSize}`
    fetch(url)
      .then(res => res.json())
      .then(data => {
        this.setState({
          movie: this.state.movie.concat(data.subjects),
          totalPage: Math.ceil(data.total/this.setState.pageSize),
          isLoading: false
        })
      })
    
    // setTimeout(() => {
    //   const data = require('../../data/in_theaters.json')
    //   this.setState({
    //     movie: data.subjects,
    //     totalPage: Math.ceil(data.total/this.setState.pageSize),
    //     isLoading: false
    //   })
    // },1000)
  }
  
  // 判断是否还在加载，渲染所有列表
  renderList = () => {
    if (this.state.isLoading){
      return <ActivityIndicator size="large" color="gray"></ActivityIndicator>
    } else {
      return <FlatList data={this.state.movie}
                       renderItem={this.renderItem}
                       keyExtractor={item => item.id}
                       ItemSeparatorComponent={this.renderSeparator}
                       onEndReachedThreshold={0.5} onEndReached={this.onLoadNextPage}>
      </FlatList>
    }
  }
  
  // 单个列表
  renderItem = ({item}) => {
    return <TouchableHighlight onPress={()=>{Actions.movieDetail({id:item.id})}}>
      <View style={{flexDirection:'row',margin:10}}>
        <Image source={{uri:item.images.small}} style={{width:100,height:120,marginRight:10}}></Image>
        <View style={{justifyContent:'space-around'}}>
          <Text>电影名称：{item.title}</Text>
          <Text>电影类型：{item.genres}</Text>
          <Text>制作年份：{item.year}年</Text>
          <Text>豆瓣评分：{item.rating.average}年</Text>
        </View>
      </View>
    </TouchableHighlight>
  }
  
  // 分割器
  renderSeparator = () => {
    return <View style={{borderTopColor:'#ccc',borderTopWidth:1,marginLeft:10,marginRight:10}}></View>
  }
  
  // 加载下一页数据
  onLoadNextPage = () => {
    var nowPage = this.state.nowPage+1
    if (nowPage > this.state.totalPage){
      return
    }
    this.setState({
      nowPage: nowPage
    },()=>{
      this.getMoviesByPage()
    })
    
  }
}

export default MovieList;
